<?php
namespace H5\Controller;

use Common\Common\CommonController;
use Org\Wechat\WechatAuth;

/**
 * 下单
 * @author lanxuebao
 *
 */
class PayController extends CommonController
{
	/**
	 * 订单确认VIEW
	 */
	public function confirm(){
		if(empty($_POST['products'])){
			exit('<script>window.location.href="/h5/mall";</script>');
		}
		
		$login = $this->user();
		$Model = D('PayConfirm');
		$data = $Model->confirm($_POST, $login);
		
		if(empty($data)){
			$this->error($Model->getError());
		}
		
		$assign = array(
			'has_error'    => $data['has_error'], 
			'error_msg'    => $data['error_msg'],
			'groups'       => $data['groups']
		);
		
		$this->assign($assign);
		$this->assign('json_data', json_encode($data));
		
		$this->display();
	}
	
	/**
	 * 计算运费
	 */
	public function freightFee(){
		$Model = new \Common\Model\ExpressModel();
		$data = $Model->getFreightFee($_POST['products'], $_POST['address']);
		$this->ajaxReturn($data);
	}
	
	/**
	 * 提交订单
	 */
	public function order(){
		$login = $this->user();
		$Model = D('PayOrder');
		$data = $Model->order($_POST['address'], $_POST['groups'], $login, $_POST['from']);
		if(empty($data)){
			$this->error($Model->getError());
		}
		
		$this->ajaxReturn($data);
	}
	
	/**
	 * 订单二次支付
	 * @param unknown $tid
	 */
	public function _empty($tid){
		$Model = D("Common/PayOrder");
		$trade = $Model->getTradeByTid($tid);
		
		if(empty($trade)){
			$this->error($Model->getError());
		}else if($trade['status'] != 'topay'){
		    redirect('/h5/order/detail?tid='.$trade['tid'], 0);
		}
		
		$login = $this->user();
		$data = $Model->getToPay($trade);
		$trade = $data['trade'];

		if(IS_POST){
			if($data['has_error']){
				$this->error($data['error_msg']);
			}
			
			// 领取赠品 - 是否需要收货地址
			if(empty($trade['receiver_mobile'])){
				if(empty($_POST['address']['receiver_name']) || empty($_POST['address']['receiver_mobile']) || empty($_POST['address']['receiver_city']) || empty($_POST['address']['receiver_detail'])){
					$this->error('收货地址不能为空');
				}else{
					$Model->setReceiver($tid, $_POST['address']);
				}
			}
			
			// 如果需要支付
			if($trade['payment'] > 0){
				$wxpay = $Model->wxpay($trade, $login);
				if($wxpay['return_code'] == 'FAIL' || $wxpay['result_code'] == 'FAIL'){
					$this->error('支付失败:'.$wxpay['return_msg']);
				}else{
					$this->success($wxpay);
				} 
			}else{
				$Model->pay($trade);
			}
			
			$this->success();
		}
		
		if(empty($trade['receiver_name'])){
			$address = D('Address')->getDefault($trade['buyer_id']);
			$this->assign('address', $address);
		}

		$this->assign(array(
			'trade' => $trade,
			'has_error' => $data['has_error']
		));
		
		$this->display('index');
	}
	
	/**
	 * 积分兑换微信红包
	 */
	public function redpack(){
		$buyer = $this->user("id, nickname, openid, subscribe");
		$Model = D('PayRedPack');
		$trade = $Model->exchange($buyer, $this->shop, $_POST['product_id']);
		if(empty($trade)){
			$this->error($Model->getError());
		}
		$this->ajaxReturn($trade);
	}
	
	/**
	 * 代理规则
	 */
	public function rule(){
		$user = $this->user('wx.headimgurl, member.nickname, member.mobile, member.id, member.balance,(member.balance-member.no_balance) AS can_balance, member.agent_level,
				member.sex, member.province_id, member.city_id, member.county_id, member.address AS detail');
		
		$agent_level = $user['agent_level'];
		$agent = M('agent')->where("level=3")->find();
		
		$this->assign('agent_level',$agent_level);
		$this->assign('agent',$agent);
		$this->assign('user',$user);
		$this->display();
	}
	
	/**
	 * 代理商充值
	 */
	public function payagent(){
		$my = $this->user('id, pid, agent_level, openid');
		if($my['agent_level'] > 0){
			$this->error('您已成为会员，无需充值！');
		}
		
		//获取代理商支付信息
		$agent = M('agent')->where('level=3')->find();
		if(empty($agent)){
			$this->error('暂无数据！');
		}
		
		//代理商充值订单数据
		$idwork = new \Org\IdWork();
		$recharge = array(
			'tid'            => $idwork->nextId(),
			'status'         => 'topay',
			'buyer_id'       => $my['id'],
			'buyer_openid'   => $my['openid'],
			'agent_level'    => $agent['level'],
			'once_amount'    => $agent['once_amount'],
			'created'        => date('Y-m-d H:i:s')
		);
		
		//数据整理 拉去微信支付功能
		$wxpay = D('Order')->createWxPayOrder(array(
			'body'       => '升级为'.$agent['title'],
			'detail'     => '升级为'.$agent['title'],
			'order_no'   => $recharge['tid'],
			'openid'     => $recharge['buyer_openid'],
			'attach'     => $my['id'],
			'time_start' => date('YmdHis'),
			'time_expire'=> date('YmdHis', strtotime('+3 hours')),
			'total_fee'  => $agent['once_amount'],
			'notify_url' => U('/service/Wxagentnotify', '', true, true),
		));
		
		if($wxpay['result_code'] == 'FAIL' || $wxpay['return_code'] == 'FAIL'){
			$this->error('生成微信支付失败');
		}

		//查询登录人信息
		$MemberModel = M('member');
		//推荐费用记录
		$agentDetail = array(
			'0' => array(
				'id'          => $my['id'],
				'agent_level' => $my['agent_level'],
				'money'       => $agent['self_amount']
		   ));
		
		// 查找上级推荐人
		$pid = $my['pid'];
		$level = 1;
		while ($pid > 0 && isset($agent['parent'.$level.'_amount'])){
			$parent = $MemberModel->field("id, pid, agent_level")->find($pid);
			if(empty($parent)){
				$pid = 0;
				break;
			}
			
			$money = $agent['parent'.$level.'_amount'];
			$agentDetail[$level] = array(
				"id"          => $parent['id'],
				"agent_level" => $parent['agent_level'],
				'money'       => ($money > 0 && $parent['agent_level'] > 0) ? $money : 0
			);
			$pid = $parent['pid'];
			$level++;
		}
		
		//保存代理商充值数据
		$recharge['detail'] = json_encode($agentDetail);
		$result = M('member_recharge')->add($recharge);
		if($result <= 0){
			$this->error('操作失败！');
		}

		$wxpay['tid'] = $recharge['tid'];
		$this->success($wxpay);
	}
	
	/**
	 * 充值成功后发送提醒消息
	 */
	public function agetnMessage(){
		ignore_user_abort(true);
		header('X-Accel-Buffering: no');
		header('Content-Length: '. strlen(ob_get_contents()));
		header("Connection: close");
		header("HTTP/1.1 200 OK");
		ob_end_flush();
		flush();

		$tid = addslashes($_REQUEST['tid']);
		if(empty($tid)){
			return;
		}

		$Model = new \Common\Model\BaseModel();
		
		//获取充值订单信息
		$recharge = $Model->query("SELECT * FROM member_recharge WHERE tid='{$tid}'");
		if(empty($recharge)){
			return;
		}
		$recharge = $recharge[0];

		// 人员关系
		$list = json_decode($recharge['detail'], true);
		$msgDate = date('Y年m月d日 H:i');
		$message = null;
		$wechatAuthList = array();
		foreach($list as $level=>$item){
			if($item['money'] <= 0 && $item['id'] != $recharge['buyer_id']){ // 充值人
				continue;
			}
			
			$wxUser = $Model->getWXUserConfig($item['id']);
			$config = $wxUser['config'];
			
			if($item['id'] == $recharge['buyer_id']){ // 充值人
				$agent = $Model->agentLevel();
				$first = '恭喜您成为本平台'.$agent[$recharge['agent_level']]['title'].'！';
				$remark = '';
				if($item['money'] > 0){
					$remark .= '系统赠送您'.sprintf('%.2f', $item['money']).'积分，';
				}
				$remark .= '赶紧去商城享受'.$agent[$recharge['agent_level']]['price_title'].'优惠价吧！';
				$message = array(
					'template_id' => $config['WX_TEMPLATE']['TM00891'],
					'url'  => $config['HOST'].'/h5/mall',
					'data' => array(
						'first'   => array('value' => $first, 'color' => '#173177'),
						'grade1'  => array('value' => $agent[$item['agent_level']]['title']),
						'grade2'  => array('value' => $agent[$recharge['agent_level']]['title']),
						'time'    => array('value' => $msgDate),
						'remark'  => array('value' => $remark)
					)
				);
			}else{
				$message = array(
					'template_id' => $config['WX_TEMPLATE']['TM00335'],
					'url' => $config['HOST'].'/h5/balance',
					'data' => array(
						'first'        => array('value' => '您有新积分到账，详情如下。', 'color' => '#173177'),
						'account'      => array('value' => $wxUser['name']),
						'time'         => array('value' => $msgDate),
						'type'         => array('value' => $level.'级好友冲值升级'),
						'creditChange' => array('value' => '到账'),
						'number'       => array('value' => sprintf('%.2f', $item['money']).'积分'),
						'creditName'   => array('value' => '积分'),
						'amount'       => array('value' => '***'),
						'remark'       => array('value' => '积分已到账，点击查看详情。')
					)
				);
			}
			
			$wechatAuth = isset($wechatAuthList[$config['WEIXIN']['appid']]) ? $wechatAuthList[$config['WEIXIN']['appid']] : new WechatAuth($config['WEIXIN']);
			$wechatAuthList[$config['WEIXIN']['appid']] = $wechatAuth;
			$result = $wechatAuth->sendTemplate($wxUser['openid'], $message);
		}
	}
	
	/**
	 * 下单支付成功后发送消息（接收人不明确）
	 */
	public function order_notify(){
		ignore_user_abort(true);
		header('X-Accel-Buffering: no');
		header('Content-Length: '. strlen(ob_get_contents()));
		header('Connection: close');
		header('HTTP/1.1 200 OK');
		ob_end_flush();
		flush();
		set_time_limit(120);

		$where = '';
		$tidStr = addslashes($_POST['trades']);
		if(!empty($_POST['trades'])){
			$where = "trade.tid IN (".$tidStr.")";
		}else{
			return;
		}
		
		$Model = new \Common\Model\BaseModel();
		
		$sql = "SELECT trade.tid, profit.mid, SUM(profit.total_fee) as total_fee, trade.buyer_nick, trade.buyer_openid, member.nickname, member.balance
				FROM mall_trade AS trade
				INNER JOIN mall_trade_difference AS profit ON profit.tid=trade.tid
				INNER JOIN member ON member.id=profit.mid
				WHERE {$where}
				GROUP BY trade.tid";
		$list = $Model->query($sql);
		if(count($list) == 0){
		    exit('');
		}

		// 1688下单
		$alilist = $Model->query("SELECT tid FROM mall_trade WHERE tid in({$tidStr}) AND `type`='1688' AND `status`='tosend'");
		if(!empty($alilist)){
		    $alibaba = new \Common\Model\AlibabaModel();
		    foreach ($alilist as $item){
		        $alibaba->commitOrder($item['tid']);
		    } 
		}
		
		// 发送消息
	    $wxUser = $Model->getWXUserConfig($list[0]['mid'], $list[0]['buyer_openid']);
	    if(empty($wxUser['config'])){
	        exit('');
	    }
	    
	    $WechatAuth = new WechatAuth($wxUser['config']['WEIXIN']);
	    $message = array(
	        'template_id' => $wxUser['config']['WX_TEMPLATE']['TM00335'],
	        'url' => '',
	        'data' => array(
	            'first'    => array('value' => '您有新积分到账，详情如下。', 'color' => '#173177'),
	            'account'  => array('value' => ''),
	            'time'     => array('value' => date('Y年m月d日 H:i')),
	            'type'     => array('value' => '好友下单赠送'),
	            'creditChange' => array('value' => '赠送'),
	            'number'       => array('value' => '***'),
	            'creditName'   => array('value' => '积分'),
	            'amount'       => array('value' => '***'),
	            'remark'       => array('value' => '好友【'.$list[0]['buyer_nick'].'】下单赠送，点击查看详情。')
	        )
	    );
	     
	    $url = $wxUser['config']['HOST'].'/h5/order/detail?tid=';
	    foreach($list as $profit){
	        $message['url']   = $url.$profit['tid'];
	        $message['data']['account']['value'] = $profit['nickname'];
	        $message['data']['number']['value']  = sprintf('%.2f', $profit['total_fee']);
	        $result[] = $WechatAuth->sendTemplate($wxUser['openid'], $message);
	    }
	}
}
?>